<template>
    <div>
        <el-form :model="registerForm" :rules="fieldRules" ref="registerForm" label-position="left" label-width="15px"
                 class="demo-ruleForm register-container">
            <h2 class="title" style="padding-left:22px;">系统注册</h2>
            <el-form-item label=" " prop="username">
                <el-input type="text" v-model="registerForm.username" auto-complete="off"
                          placeholder="账户，登录用户名"></el-input>
            </el-form-item>
            <el-form-item label=" " prop="alias">
                <el-input type="text" v-model="registerForm.alias" auto-complete="off"
                          placeholder="昵称，展示名称，不填默认登录名"></el-input>
            </el-form-item>
            <el-form-item label=" " prop="email">
                <el-input type="text" v-model="registerForm.email" auto-complete="off" placeholder="邮箱"></el-input>
            </el-form-item>
            <el-form-item>
                <el-col :span="12">
                    <el-form-item label=" " prop="emailCode">
                        <el-input type="text" v-model="registerForm.emailCode" auto-complete="off" placeholder="邮箱验证码"></el-input>
                    </el-form-item>
                </el-col>
                <el-col class="line" :span="1">&nbsp;</el-col>
                <el-col :span="11">
                    <el-form-item>
                        <el-button @click="sendEmail" :loading="sendEmailLoading" :disabled="sendEmailButtonDisabled">{{emailWaitTime == 60?'发送验证码':'等待('+emailWaitTime+')'}}</el-button>
                    </el-form-item>
                </el-col>
            </el-form-item>
            <el-form-item label=" " prop="password">
                <el-input type="password" v-model="registerForm.password" auto-complete="off"
                          placeholder="密码"></el-input>
            </el-form-item>
            <!--<el-form-item label=" " prop="passwordAgain">-->
                <!--<el-input type="password" v-model="registerForm.passwordAgain" auto-complete="off"-->
                          <!--placeholder="确认密码"></el-input>-->
            <!--</el-form-item>-->
            <!--<el-form-item>-->
                <!--<el-col :span="12">-->
                    <!--<el-form-item label=" " prop="captcha">-->
                        <!--<el-input type="test" v-model="registerForm.captcha" auto-complete="off"-->
                                  <!--placeholder="验证码, 单击图片刷新"-->
                                  <!--style="width: 100%;">-->
                        <!--</el-input>-->
                    <!--</el-form-item>-->
                <!--</el-col>-->
                <!--<el-col class="line" :span="1">&nbsp;</el-col>-->
                <!--<el-col :span="11">-->
                    <!--<el-form-item>-->
                        <!--<img style="width: 100%;" class="pointer" :src="captchaImgSrc" @click="refreshCaptcha">-->
                    <!--</el-form-item>-->
                <!--</el-col>-->
            <!--</el-form-item>-->
            <el-form-item style="width:100%;" class="ly-button-center">
                <el-button type="primary" style="width:48%;" @keyup.enter.native="register('registerForm')"
                           @click.native.prevent="register('registerForm')" :loading="loading">注 册
                </el-button>
                <el-button type="primary" style="width:40%;" @click.native.prevent="reset">重 置</el-button>
            </el-form-item>

            <div class="login-tips">
                已有账号？
                <el-button type="text" @click="$router.push({ path: '/login' })">账号登录</el-button>
                <el-button type="text" @click="$router.push({ path: '/login/email' })">邮箱验证码登录</el-button>
            </div>
        </el-form>
    </div>
</template>

<script>
    import Cookies from "js-cookie"
    import {getUUID} from "@/utils"
    import {isEmail} from "@/utils/validate"

    export default {
        data() {

            //自定义校验规则 - 账户检测
            const usernameValidator = (rule, value, callback) => {
                //字母开头+数字
                let preg = /^([a-zA-Z])[a-z0-9]+$/
                if(!preg.test(value)){
                    callback(new Error('账户只能由字母和数字组合，且字母开头'));
                }
                this.$api.Login.checkUsername(value).then((res) => {  // 调用登录接口
                    if (res && res.code === 0) {
                        callback();
                    }else{
                        callback(new Error('账户已存在'));
                    }
                })
            };

            return {
                loading: false,
                sendEmailLoading: false,
                registerForm: {
                    username: '',
                    alias: '',
                    email: '',
                    emailCode: '',
                    password: '',
                    passwordAgain: '',
                    captcha: '',
                },
                fieldRules: {
                    username: [
                        { required: true, message: '请填写账号', trigger: 'blur' },
                        { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' },
                        { validator: usernameValidator, trigger: 'blur' },
                    ],
                    email: [
                        { required: true, message: '请填写个人邮箱', trigger: 'blur' },
                        { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
                    ],
                    emailCode: [
                        { required: true, message: '填写邮箱验证码', trigger: 'blur' },
                    ],
                    password: [
                        { required: true, message: '请制定密码', trigger: 'blur' }
                    ],
                    passwordAgain: [
                        { required: true, message: '请确认你所制定的密码', trigger: 'blur' }
                    ],
                    captcha: [
                        {required: true, message: '请输入验证码', trigger: 'blur'}
                    ],
                },
                checked: true,
                captchaImgSrc: "",

                emailWaitTime :60, //发送邮箱后等待时间
                sendEmailButtonDisabled:false, //发送邮件按钮是否可用
            }
        },
        methods: {
            register(formName) {
                this.loading = true
                this.$refs[formName].validate((valid) => {
                    if (!valid) {
                        this.loading = false
                        return false;
                    }
                    // if(this.registerForm.password !== this.registerForm.passwordAgain){
                    //     this.$message({ message: '密码不一致！', type: 'error' })
                    //     this.loading = false
                    //     return false;
                    // }

                    this.$api.Login.register(this.registerForm).then((res) => {  // 调用登录接口
                        if (res && res.code === 0) {
                            this.$message({message: '注册成功', type: 'success'})
                            this.$router.push({
                                path: '/login',
                                query: {username: this.registerForm.username}
                            })
                        }else{
                            this.$message({ message: res.msg, type: 'error' })
                        }
                        this.loading = false
                    }).catch((res) => {
                        this.$message({ message: res.message, type: 'error' })
                        this.loading = false
                    })
                });
            },

            refreshCaptcha: function(){
                this.registerForm.uuid = getUUID();
                this.captchaImgSrc = `${this.global.baseUrl}/captcha.jpg?uuid=${this.registerForm.uuid}`;
            },

            reset() {
                this.$refs['registerForm'].resetFields();
            },
            //发送邮箱
            sendEmail(){
                this.$refs['registerForm'].validateField('email', (valid) => {

                    // valid 校验信息
                    if (valid) {
                        return false;
                    }

                    this.sendEmailLoading = true
                    this.registerForm.emailUuid = getUUID();
                    this.$api.Login.send({
                        email:this.registerForm.email,
                        uuid:this.registerForm.emailUuid,
                        type:0
                    }).then(res =>{
                        if (res && res.code === 0) {
                            this.$message({message: '发送成功！', type: 'success'});
                            this.sendEmailButtonDisabled = true;
                            let timer = setInterval(()=>{
                                if(this.emailWaitTime == 0){
                                    clearInterval(timer);
                                    this.sendEmailButtonDisabled = false;
                                    this.emailWaitTime = 60;
                                    return;
                                }
                                this.emailWaitTime --;
                            },1*1000);
                        }else{
                            this.$message({ message: res.msg, type: 'error' })
                        }
                        this.sendEmailLoading = false
                    }).catch((res) => {
                        this.$message({ message: res.msg, type: 'error' })
                        this.sendEmailLoading = false
                    });
                });
            },

        },
        mounted() {
            // this.refreshCaptcha()
        },
        created() {
            var _self = this
            document.onkeydown = function(e) {
                var key = window.event.keyCode
                if (key === 13) {
                    _self.register('registerForm')
                }
            }
        },
        destroyed(){
            document.onkeydown = undefined;
        }
    }
</script>

<style scoped>
    .register-container {
        -webkit-border-radius: 5px;
        border-radius: 5px;
        -moz-border-radius: 5px;
        background-clip: padding-box;
        margin: 20px auto;
        width: 280px;
        padding: 35px 15px;
        background: #fff;
        border: 1px solid #eaeaea;
        box-shadow: 0 0 25px #cac6c6;
    }

    .title {
        margin: 0px auto 30px auto;
        text-align: center;
        color: #505458;
    }

    .ly-button-center {
        text-align: center;
    }
</style>
